package com.itheima.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @Author 请不要叫我高司令
 * @Date 2022/3/27 17:43
 * @Version 1.0
 */

@Component
public class RedisToMongoJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0 0/1 * * * ?")// 老师用1分钟
    public void movementJob() {

        System.out.println("推荐动态start....");

        //读取redis
        Set<String> keys = stringRedisTemplate.keys("MOVEMENTS_RECOMMEND_*");

        if (CollectionUtil.isNotEmpty(keys)) {

            for (String key : keys) {

                //获取用户id
                String userIdStr = key.replace("MOVEMENTS_RECOMMEND_", "");
                long userId = Long.parseLong(userIdStr);

                //获取推荐给此用户的动态id
                String pidsStr = stringRedisTemplate.opsForValue().get(key);

                String[] pidArray = pidsStr.split(",");
                //删除redis中的这个key
                stringRedisTemplate.delete(key);
                //删除mongo中推荐给这个用户的数据，注意不是全部删除
                mongoTemplate.remove(new Query(Criteria.where("userID").is(userId)), RecommendMovement.class);

                //遍历pidArray
                for (String pidStr : pidArray) {

                    long pid = Long.parseLong(pidStr);

                    //封装推荐动态实体
                    RecommendMovement recommendMovement = new RecommendMovement();
                    recommendMovement.setCreated(System.currentTimeMillis());//推荐时间
                    recommendMovement.setUserId(userId);//推荐给谁？
                    recommendMovement.setPid(pid);//大数据动态id
                    //获取动态id
                    Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(pid)), Movement.class);
                    recommendMovement.setPublishId(movement.getId());//MongoDb的动态id
                    recommendMovement.setScore(RandomUtil.randomDouble(70, 99));

                    //保存实体
                    mongoTemplate.save(recommendMovement);

                }

            }

        }

        System.out.println("推荐动态end....");

    }

}
